import {getUserHeadUrl, login, logout} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {queryResource} from "@/api/resource";
import Layout from '@/layout'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''}
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const allResources = {
  '@/layout': () => import('@/layout'),
  '@/views/person/myDesign': () => import('@/views/person/myDesign'),
  '@/views/person/collection': () => import('@/views/person/collection'),
  '@/views/person/personalInformation': () => import('@/views/person/personalInformation'),
  '@/views/lifeSquare/lifeShare': () => import('@/views/lifeSquare/lifeShare'),
  '@/views/lifeSquare/withMatching': () => import('@/views/lifeSquare/withMatching'),
  '@/views/soulListen/latestRecommended': () => import('@/views/soulListen/latestRecommended'),
  '@/views/soulListen/soulSharing': () => import('@/views/soulListen/soulSharing'),
  '@/views/resourceManagement/role': () => import('@/views/resourceManagement/role'),
  '@/views/resourceManagement/menuPermission': () => import('@/views/resourceManagement/menuPermission'),
  '@/views/resourceManagement/backSecurity': () => import('@/views/resourceManagement/backSecurity'),
  '@/views/userManagement/account': () => import('@/views/userManagement/account'),
  '@/views/userManagement/userPermission': () => import('@/views/userManagement/userPermission'),
  '@/views/operationAnalysis/userBehavior': () => import('@/views/operationAnalysis/userBehavior'),
  '@/views/operationAnalysis/resourceAccess': () => import('@/views/operationAnalysis/resourceAccess'),
  '@/views/operationAnalysis/operationIndicator': () => import('@/views/operationAnalysis/operationIndicator'),
  '@/views/operationAnalysis/communityActivity': () => import('@/views/operationAnalysis/communityActivity'),
  '@/views/systemManagement/contentReview': () => import('@/views/systemManagement/contentReview'),
  '@/views/systemManagement/feedback': () => import('@/views/systemManagement/feedback'),
  '@/views/systemManagement/systemResource': () => import('@/views/systemManagement/systemResource'),
  '@/views/eventTracking': () => import('@/views/eventTracking'),
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.body.data)
        setToken(response.body.data)
        getUserHeadUrl().then(res => {
          commit('SET_AVATAR', res.body.data)
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      queryResource(state.token).then(response => {
        const { data } = response.body
        if (!data) {
          return reject('验证失败，请重新登录')
        }

        resetRouter()
        const menus = getMenusFromResources(data)
        for (let i=0;i<menus.length;i++) {
          router.options.routes.push(menus[i])
          router.addRoutes([menus[i]])
        }
        // const { name } = data
        //
        // commit('SET_NAME', name)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

function getMenusFromResources(resources) {
  const menus = []
  menus.push({
    path: '/',
    component: Layout,
    name: 'dashboard',
    redirect: '/home',
    meta: {title: '主页', icon: 'el-icon-s-home'},
    children: [{
      path: 'home',
      name: 'home',
      component: () => import('@/views/dashboard/index'),
      meta: {title: '主页', icon: 'el-icon-s-home'}
    }]
  })

  for (let i=0;i<resources.length;i++) {
    menus.push(getResourceMenu(resources[i]))
  }
  menus.push({path: '*', redirect: '/404', hidden: true})
  return menus
}

// 获取单个资源对应的菜单
function getResourceMenu(resource) {
  if (!resource.children) {
    return {
      path: resource.url,
      component: allResources[resource.src],
      name: resource.name,
      meta: { title: resource.name, icon: resource.icon }
    }
  }
  const menu = {
    path: resource.url,
    component: allResources[resource.src],
    name: resource.name,
    meta: { title: resource.name, icon: resource.icon },
    children: []
  }
  for (let i = 0; i < resource.children.length; i++) {
    const temp = getResourceMenu(resource.children[i])
    menu.children.push(temp)
  }
  if (menu.children.length === 0) {
    delete menu.children
    menu.component = allResources[resource.src]
  }
  return menu
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

